/**
 * @description 考试配置文件
 * @author 张一依有把越女剑
 * @date 2025-04-16
 */

// 考试配置
export const examConfig = {
	// 基础配置
	basic: {
		defaultDuration: 15, // 默认考试时长（分钟）
		questionsPerExam: 10, // 每次考试题目数量
		passingScore: 60, // 及格分数
		maxAttempts: 3, // 最大考试次数
		autoSubmit: true, // 时间到自动提交
		allowReview: true, // 允许查看答案解析
	},
	
	// 难度配置
	difficulty: {
		easy: {
			name: '简单',
			percentage: 60, // 简单题目占比
			timePerQuestion: 60 // 每题建议时间（秒）
		},
		medium: {
			name: '中等',
			percentage: 30,
			timePerQuestion: 90
		},
		hard: {
			name: '困难',
			percentage: 10,
			timePerQuestion: 120
		}
	},
	
	// 分类配置
	categories: {
		'基础知识': {
			name: '安全生产基础知识',
			color: '#1E90FF',
			icon: '📚'
		},
		'法律法规': {
			name: '安全生产法律法规',
			color: '#FF6B6B',
			icon: '⚖️'
		},
		'操作规程': {
			name: '安全操作规程',
			color: '#4ECDC4',
			icon: '🔧'
		},
		'应急处理': {
			name: '应急处理措施',
			color: '#45B7D1',
			icon: '🚨'
		},
		'防护用品': {
			name: '个人防护用品',
			color: '#96CEB4',
			icon: '🦺'
		}
	},
	
	// 评分标准
	scoring: {
		excellent: { min: 90, label: '优秀', color: '#52C41A', icon: '🏆' },
		good: { min: 80, label: '良好', color: '#1890FF', icon: '👍' },
		average: { min: 70, label: '中等', color: '#FAAD14', icon: '👌' },
		pass: { min: 60, label: '及格', color: '#FA8C16', icon: '✅' },
		fail: { min: 0, label: '不及格', color: '#F5222D', icon: '❌' }
	}
}

// 获取评分等级
export function getScoreLevel(score) {
	const { scoring } = examConfig
	if (score >= scoring.excellent.min) return scoring.excellent
	if (score >= scoring.good.min) return scoring.good
	if (score >= scoring.average.min) return scoring.average
	if (score >= scoring.pass.min) return scoring.pass
	return scoring.fail
}

// 根据难度分布生成题目
export function generateExamByDifficulty(questionBank, totalQuestions = 10) {
	// 安全检查
	if (!questionBank || !Array.isArray(questionBank) || questionBank.length === 0) {
		console.error('Question bank is invalid or empty')
		return []
	}

	// 为没有难度属性的题目设置默认难度
	const normalizedQuestions = questionBank.map((q, index) => {
		// 智能分配难度和分类
		let difficulty = q.difficulty || 'medium'
		let category = q.category || '基础知识'

		// 如果没有设置难度，根据题目位置智能分配
		if (!q.difficulty) {
			if (index < 15) {
				difficulty = 'easy'
			} else if (index < 35) {
				difficulty = 'medium'
			} else {
				difficulty = 'hard'
			}
		}

		// 如果没有设置分类，根据题目内容智能分配
		if (!q.category) {
			const questionText = q.question.toLowerCase()
			if (questionText.includes('法') || questionText.includes('条例') || questionText.includes('规定')) {
				category = '法律法规'
			} else if (questionText.includes('操作') || questionText.includes('作业') || questionText.includes('使用')) {
				category = '操作规程'
			} else if (questionText.includes('应急') || questionText.includes('急救') || questionText.includes('事故')) {
				category = '应急处理'
			} else if (questionText.includes('防护') || questionText.includes('安全帽') || questionText.includes('安全带')) {
				category = '防护用品'
			}
		}

		return {
			...q,
			difficulty,
			category,
			explanation: q.explanation || `这是一道关于${category}的${difficulty === 'easy' ? '基础' : difficulty === 'medium' ? '中等' : '高级'}题目。`
		}
	})

	const { difficulty } = examConfig
	const easyCount = Math.floor(totalQuestions * difficulty.easy.percentage / 100)
	const mediumCount = Math.floor(totalQuestions * difficulty.medium.percentage / 100)
	const hardCount = totalQuestions - easyCount - mediumCount

	// 按难度分类题目
	const easyQuestions = normalizedQuestions.filter(q => q.difficulty === 'easy')
	const mediumQuestions = normalizedQuestions.filter(q => q.difficulty === 'medium')
	const hardQuestions = normalizedQuestions.filter(q => q.difficulty === 'hard')

	// 如果某个难度的题目不够，从其他难度补充
	let selectedQuestions = []

	// 优先选择指定难度的题目
	selectedQuestions.push(...getRandomItems(easyQuestions, easyCount))
	selectedQuestions.push(...getRandomItems(mediumQuestions, mediumCount))
	selectedQuestions.push(...getRandomItems(hardQuestions, hardCount))

	// 如果题目不够，从剩余题目中随机选择
	if (selectedQuestions.length < totalQuestions) {
		const usedIds = new Set(selectedQuestions.map(q => q.id))
		const remainingQuestions = normalizedQuestions.filter(q => !usedIds.has(q.id))
		const needed = totalQuestions - selectedQuestions.length
		selectedQuestions.push(...getRandomItems(remainingQuestions, needed))
	}

	// 打乱题目顺序
	return selectedQuestions.sort(() => Math.random() - 0.5)
}

// 随机选择数组中的指定数量元素
function getRandomItems(array, count) {
	const shuffled = [...array].sort(() => Math.random() - 0.5)
	return shuffled.slice(0, Math.min(count, array.length))
}

// 计算考试统计信息
export function calculateExamStats(examRecord, questionBank) {
	const stats = {
		totalQuestions: examRecord.questions?.length || 0,
		correctAnswers: 0,
		wrongAnswers: 0,
		accuracy: 0,
		categoryStats: {},
		difficultyStats: {}
	}
	
	if (!examRecord.questions) return stats
	
	examRecord.questions.forEach(question => {
		const isCorrect = question.userAnswer === question.answer
		if (isCorrect) {
			stats.correctAnswers++
		} else {
			stats.wrongAnswers++
		}
		
		// 分类统计
		const category = question.category || '未分类'
		if (!stats.categoryStats[category]) {
			stats.categoryStats[category] = { total: 0, correct: 0 }
		}
		stats.categoryStats[category].total++
		if (isCorrect) stats.categoryStats[category].correct++
		
		// 难度统计
		const difficulty = question.difficulty || 'medium'
		if (!stats.difficultyStats[difficulty]) {
			stats.difficultyStats[difficulty] = { total: 0, correct: 0 }
		}
		stats.difficultyStats[difficulty].total++
		if (isCorrect) stats.difficultyStats[difficulty].correct++
	})
	
	stats.accuracy = stats.totalQuestions > 0 ? 
		Math.round((stats.correctAnswers / stats.totalQuestions) * 100) : 0
	
	return stats
}
